在访问linux时,首先需要使用工具类jar包:ganymed-ssh2
登录远程服务器:
public boolean login(){
//创建远程连接,默认连接端口为22,如果不使用默认,可以使用方法
//new Connection(ip, port)创建对象
Connection conn = new Connection(ip);
try {
//连接远程服务器
conn.connect();
//使用用户名和密码登录
return conn.authenticateWithPassword(usr, psword);
} catch (IOException e) {
System.err.printf("用户%s密码%s登录服务器%s失败!", usr, psword, ip);
e.printStackTrace();
}
return false;
}
/**
* 上传本地文件到服务器目录下
* @param conn Connection对象
* @param fileName 本地文件
* @param remotePath 服务器目录
*/
public void putFile(Connection conn, String fileName, String remotePath){
SCPClient sc = new SCPClient(conn);
try {
//将本地文件放到远程服务器指定目录下,默认的文件模式为 0600,即 rw,
//如要更改模式,可调用方法 put(fileName, remotePath, mode),模式须是4位数字且以0开头
sc.put(fileName, remotePath);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 下载服务器文件到本地目录
* @param fileName 服务器文件
* @param localPath 本地目录
*/
public void copyFile(Connection conn, String fileName,String localPath){
SCPClient sc = new SCPClient(conn);
try {
sc.get(fileName, localPath);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 在远程LINUX服务器上,在指定目录下,获取文件各个属性
* @param[in] conn Conncetion对象
* @param[in] remotePath 远程主机的指定目录
*/
public void getFileProperties(Conncetion conn, String remotePath){
try {
SFTPv3Client sft = new SFTPv3Client(conn);
Vector v = sft.ls(remotePath);
for(int i=0;i v = sft.ls(remotePath);
for(int i=0;i |